package wk.demo.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.luoye.bzijkplayer.R;
import com.tencent.mmkv.MMKV;

import java.lang.ref.WeakReference;
import java.util.Locale;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
import tv.danmaku.ijk.media.player.misc.ITrackInfo;
import tv.danmaku.ijk.media.player.mplayer.IMediaPlayer;
import wk.demo.bean.HistoryReadBean;
import wk.demo.tool.MyToastTool;
import wk.demo.tool.RxJavaTool;
import wk.demo.tool.WkHeartBeatTool;
import wk.demo.tool.WkLogTool;
import wk.demo.callback.OnGetRealTimeInfo;
import wk.demo.config.WkConfig;
import wk.demo.fragments.dialogFragment.WkPlayerDetailSettingFragment;
import wk.demo.fragments.dialogFragment.WkPlayerSettingFragment;
import wk.demo.tool.BrightnessTools;
import wk.demo.widget.GestureView;
import wk.demo.widget.media.IjkVideoView;
import wk.demo.widget.media.MeasureHelper;

public class VideoActivity extends BashCompatActivity {
    private Context mContext ;
    private IjkVideoView mVideoView;
    private boolean mBackPressed =false;
    private ImageView lockPlayer ;
    private TextView extInfo ;
    private WkHeartBeatTool wkHeartBeatTool = new WkHeartBeatTool();


    public static Intent newIntent(Context context, String videoPath ) {
        Intent intent = new Intent(context, VideoActivity.class);
        intent.putExtra("videoPath", videoPath);
        return intent;
    }

    public static void intentTo(Context context, String videoPath ) {
        context.startActivity( newIntent(context, videoPath ));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        mContext = this ;

        initPlayer();
        initView();
    }


    private void loadNativeLib(){
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
    }


    private void initPlayer(){
        Intent intent = getIntent();
        String mVideoPath =intent.getStringExtra("videoPath");
        String intentAction = intent.getAction();

        if (!TextUtils.isEmpty(intentAction)) {
            // 文件打开方式，的方式打开文件
            if (intentAction.equals(Intent.ACTION_VIEW)) {
                mVideoPath = intent.getDataString();
            }
        }

        if (!TextUtils.isEmpty(mVideoPath)) {
            // 保存历史记录
            new HistoryReadBean(mVideoPath).save() ;
        }

        // init player
        loadNativeLib() ;

        mVideoView =  findViewById(R.id.video_view);
        MediaController mMediaController = new MediaController(this, true);
        mVideoView.setMediaController(mMediaController);
        mVideoView.setHudView( onGetRealTimeInfo);
        mVideoView.setOnCompletionListener(onCompletionListener);

        if (mVideoPath != null){
            // 缓存视屏
            //HttpProxyCacheServer proxy = MyApplication.getProxy(mContext);
            //String proxyUrl = proxy.getProxyUrl(mVideoPath);
            mVideoView.setVideoPath(mVideoPath);
        }  else {
            WkLogTool.showLog( "Null Data Source\n");
            finish();
            return;
        }
        mVideoView.start();
    }

    private void initView(){
        extInfo =  findViewById(R.id.extInfo);
        findViewById(R.id.savePic).setOnClickListener(onClickListener);
        findViewById(R.id.showFileInfo).setOnClickListener(onClickListener);

        lockPlayer = findViewById(R.id.lockPlayer);
        lockPlayer.setOnClickListener(onClickListener);

        GestureView gestureView = findViewById(R.id.gestureView) ;
        gestureView.setCallBack(myGestureCallback);

    }


    @Override
    public void onBackPressed() {
        mBackPressed = true;
        super.onBackPressed();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mBackPressed || !mVideoView.isBackgroundPlayEnabled()) {
            mVideoView.stopPlayback();
            mVideoView.release(true);
            mVideoView.stopBackgroundPlay();
        } else {
            mVideoView.enterBackground();
        }
        IjkMediaPlayer.native_profileEnd();
    }

    private GestureView.MyGestureCallBack myGestureCallback = new GestureView.MyGestureCallBack() {

        @Override
        public void scrollToLeft( ) {

        }

        @Override
        public void scrollToRight( ) {
        }

        @Override
        public void scrollToTop(boolean isAtLeft ) {
            if(mVideoView.isScreenLocked()){
                return;
            }

            if(isAtLeft){
                getBrightnewssTool().changeBrightness(true);
            }else{
                changeVolume(true) ;
            }

        }

        @Override
        public void scrollToBottom(boolean isAtLeft ) {
            if(mVideoView.isScreenLocked()){
                return;
            }

            if(isAtLeft){
                getBrightnewssTool().changeBrightness(false);
            }else{
                changeVolume(false);
            }
        }

        @Override
        public void zoomToMax( float scale) {
        }

        @Override
        public void zoomToMin(float scale ) {
        }

        @Override
        public void zoomStop( ) {
        }

        @Override
        public void onDown(boolean isAtLeft) {

            if(isAtLeft){
                int sysTempBrightnewss= getBrightnewssTool().getScreenBrightness(  mcontext  ) ;
                int brightnessSave = MMKV.defaultMMKV().decodeInt(WkConfig.KEY_BRIGHTNESS ,-1);
                getBrightnewssTool().setCurrentBrghtnewss(  (brightnessSave== -1 ) ?  sysTempBrightnewss :  brightnessSave ) ;
            }else{
                currentVolume =  MMKV.defaultMMKV().decodeFloat(WkConfig.KEY_VOLUME ,0.5F);
            }

        }

        @Override
        public void onActionUp(boolean isAtLeft) {
            extInfo.setVisibility(View.GONE);
            if(isAtLeft){
                MMKV.defaultMMKV().encode( WkConfig.KEY_BRIGHTNESS  ,getBrightnewssTool().getCurrentBrghtnewss()) ;
            }else{
                MMKV.defaultMMKV().encode( WkConfig.KEY_VOLUME  ,currentVolume ) ;
            }

        }

        @Override
        public void doubleClick( ) {
        }

        @Override
        public void onLongPress() {
        }

        @Override
        public void onClick() {
            if(!mVideoView.isScreenLocked()){
                mVideoView.toggleMediaControlsVisiblity("onClick");
            }

        }
    };


    private float currentVolume =0.5f ;
    private void changeVolume(boolean isAdd){
        currentVolume = isAdd?   (currentVolume+ 0.02f) : (currentVolume- 0.02f) ;
        currentVolume =  currentVolume>=1 ? 1 : currentVolume ;
        currentVolume =  currentVolume <=0 ? 0 : currentVolume ;
        mVideoView.setVolume(currentVolume ,currentVolume);

        extInfo.setVisibility(View.VISIBLE);
        extInfo.setText( String.format(Locale.getDefault() ,"音量:%.2f" ,currentVolume)  );
    }


    private BrightnessTools brightnessTools ;
    private BrightnessTools getBrightnewssTool(){
        if(brightnessTools==null){
            brightnessTools= new BrightnessTools(mcontext ,extInfo) ;
        }
        return brightnessTools;
    }


    private IMediaPlayer.OnCompletionListener onCompletionListener = mp -> {
        showToastMsg("播放完成！");
    };



    private OnGetRealTimeInfo onGetRealTimeInfo = new OnGetRealTimeInfo() {
        @Override
        public void onGetRealTimeMsg(String msg1, String msg2) {
            if(wkPlayerSettingFragment ==null ){
                return;
            }
            wkPlayerSettingFragment.updateRealTimeMsg(msg1 ,msg2);

        }
    };



    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if(id==R.id.showFileInfo){
                showWkCameraDialogFragment();
            }else if(id==R.id.savePic){
                wkHeartBeatTool.startDelayedAction(new WkHeartBeatTool.HeartBeatTask() {
                    @Override
                    public void run() {
                        boolean result=mVideoView.snapshotPicture();
                        addToCompositeDisposable(Observable.just(result)
                                .compose(RxJavaTool::toSimpleObservable)
                                .subscribe(value -> {
                                       String str= value ? "截屏成功" : "截屏失败" ;
                                        MyToastTool.toastMsg(mcontext ,str);
                                }));

                    }
                } ,10);

            }else if(id==R.id.lockPlayer){
                if(mVideoView.isScreenLocked()){
                    lockPlayer.setImageResource(R.mipmap.ic_unlock);
                }else{
                    lockPlayer.setImageResource(R.mipmap.ic_lock);
                }
                mVideoView.setScreenLocked(!mVideoView.isScreenLocked());

            }
        }
    };


    public String getTracksInfo(){
        StringBuilder sb = new StringBuilder() ;
        ITrackInfo[] mTrackInfos =    mVideoView.getTrackInfo()  ;//trackHolder.getTrackInfo();
        int mIndex =0;
        if (mTrackInfos != null) {
            for(ITrackInfo trackInfo: mTrackInfos) {
               String trakInfo   = String.format(Locale.getDefault(), "# %d: %s", mIndex, trackInfo.getInfoInline());
               sb.append("\r\n").append(trakInfo);
               mIndex++ ;
            }
        }
        return sb.toString() ;
    }




    private WkPlayerSettingFragment wkPlayerSettingFragment;
    private void showWkCameraDialogFragment() {
        if (wkPlayerSettingFragment != null) {
            if (wkPlayerSettingFragment.isShowFragment()) {
                wkPlayerSettingFragment.dismiss();
            }
            wkPlayerSettingFragment = null;
        }


        wkPlayerSettingFragment = WkPlayerSettingFragment.getInstance(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                wkPlayerSettingFragment.openSwitchFragment(checkedId);
                if(checkedId==1){
                    wkPlayerSettingFragment.setMsgShow( getBaseInfo() );
                }
            }
        } ,onItemClick);
        wkPlayerSettingFragment.setMsgShow( getBaseInfo() );
        wkPlayerSettingFragment.show( getSupportFragmentManager(), WkPlayerSettingFragment.class.getSimpleName());
    }

    private WkPlayerDetailSettingFragment.OnItemClick  onItemClick= new WkPlayerDetailSettingFragment.OnItemClick(){

        @Override
        public void onRatioClick(boolean readOnly) {
            int aspectRatio = readOnly? mVideoView.getCurrentAspectRatio(): mVideoView.toggleAspectRatio();
            String aspectRatioText = MeasureHelper.getAspectRatioText(mContext, aspectRatio);
            wkPlayerSettingFragment.updateRatioInfo(aspectRatioText);
        }

        @Override
        public void onRenderClick(boolean readOnly) {
            /*int render = readOnly? mVideoView.getCurrentRenderIndex():  mVideoView.toggleRender();
            String renderText = IjkVideoView.getRenderText(mContext, render);
            wkPlayerSettingFragment.updateRenderInfo(renderText);*/
        }

        @Override
        public void onSpeedSetChange(float speed) {
            mVideoView.setSpeed(speed);
        }

    };



    private String getBaseInfo(){
        String msg =  mVideoView.showMediaInfo();
        msg+="\r\n\r\n轨道信息：" ;
        msg+=  getTracksInfo();
        return msg ;
    }

}


